﻿# coding: utf-8
import weakref

class CHistoryManager:
    """
    The 'HISTORY_MANAGER' manages a command list.
    User can run to any position of the command list to suit 'Undo/Redo' purpose.
    """

    def __init__(self):
        self._maxHistory = 10
        self._currentPos = 0

        self._cmdList = []

    def SetMaxHistory(self, max):
        self._maxHistory = max

    def GetCurrentPos(self):
        self._currentPos

    def DoCmd(self, maxCmd):
        while maxCmd > 0 and self._currentPos < len(self._cmdList):
            self._cmdList[self._currentPos].DoCmd()
            self._currentPos += 1
            maxCmd -= 1

    def UndoCmd(self, maxCmd):
        while maxCmd > 0 and self._currentPos > 0:
            if not self._cmdList[self._currentPos - 1].UndoCmd():
                self._cmdList.pop(self._currentPos - 1)
            self._currentPos -= 1
            maxCmd -= 1

    def RunCommand(self, cmd):
        """
        Push a new command and run it

        Parameters:
        @param cmd - the new command object
        """

        assert(self._currentPos <= len(self._cmdList))

        if self._currentPos == len(self._cmdList):
            self._cmdList.append(cmd)
        else:
            self._cmdList[self._currentPos] = cmd
            self._cmdList = self._cmdList[:self._currentPos + 1]

        self.DoCmd(1)
        
    def GetCurrentCmdRef(self):
        """ Get the weak reference of the current command """
        
        if self._currentPos > 0 and self._currentPos <= len(self._cmdList):
            return weakref.ref(self._cmdList[self._currentPos - 1])
            
        return None

__builtins__['HISTORY_MANAGER'] = CHistoryManager()
